package com.rc.activity;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.dao.tbl_Settings;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.model.Model;
import com.rc.model.TaskType;
import com.rc.object.BaseObject;
import com.rc.object.ReceiptObj;
import com.rc.util.Util;
import com.telpoo.frame.model.TaskParams;
import com.telpoo.frame.ui.BaseActivity;

public class ReceiptConverter extends BaseActivity implements OnClickListener {

	public static void callIntent(Context ct, ReceiptObj objReceipt) {
		Intent it = new Intent(ct, ReceiptConverter.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("RECEIPT_OBJ", objReceipt);
		it.putExtras(bundle);
		ct.startActivity(it);
	}

	private LinearLayout llSave, llCancel, llReset, llBottom, llContent;
	private Spinner spConverterNow;
	private ProgressBar pbLoad;
	private TextView txtHomeDiscount, txtHomeTotal, txtHomeTax, txtPurDate,
			txtHomeSubTotal, txtHomeCurrency, txtRate, txtConvertSubTotal,
			txtConvertTax, txtConvertTotal, txtConvertDiscount;

	private ReceiptObj objReceipt;
	private int row = 0;
	private String homecurrency;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.receipt_conventer);

		spConverterNow = (Spinner) findViewById(R.id.spConverterNow);
		llSave = (LinearLayout) findViewById(R.id.llSave);
		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		llBottom = (LinearLayout) findViewById(R.id.llBottom);
		llContent = (LinearLayout) findViewById(R.id.llContent);
		txtHomeDiscount = (TextView) findViewById(R.id.txtHomeDiscount);
		txtHomeTotal = (TextView) findViewById(R.id.txtHomeTotal);
		txtHomeTax = (TextView) findViewById(R.id.txtHomeTax);
		txtHomeSubTotal = (TextView) findViewById(R.id.txtHomeSubTotal);
		txtConvertDiscount = (TextView) findViewById(R.id.txtConvertDiscount);
		txtConvertTotal = (TextView) findViewById(R.id.txtConvertTotal);
		txtConvertTax = (TextView) findViewById(R.id.txtConvertTax);
		txtConvertSubTotal = (TextView) findViewById(R.id.txtConvertSubTotal);
		txtPurDate = (TextView) findViewById(R.id.txtPurchaseDate);
		pbLoad = (ProgressBar) findViewById(R.id.pbLoad);

		txtHomeCurrency = (TextView) findViewById(R.id.txtHomeCurrency);
		txtRate = (TextView) findViewById(R.id.txtRate);

		// add data Ui
		addDataUI();

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getAssetCurrency());
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spConverterNow.setAdapter(dataAdapter);
		spConverterNow.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {

				String text = spConverterNow.getItemAtPosition(position)
						.toString();
				String textHomeCurrency = txtHomeCurrency.getText().toString();
				if (!(textHomeCurrency.trim()).equals(text.trim())) {
					callService(text, txtHomeCurrency.getText().toString());
				} else {
					llContent.setVisibility(View.VISIBLE);
					llBottom.setVisibility(View.VISIBLE);
					pbLoad.setVisibility(View.GONE);
					txtConvertDiscount.setText(txtHomeDiscount.getText()
							.toString());
					txtConvertSubTotal.setText(txtHomeSubTotal.getText()
							.toString());
					txtConvertTax.setText(txtHomeTax.getText().toString());
					txtConvertTotal.setText(txtHomeTotal.getText().toString());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			};
		});
		spConverterNow.setSelection(row);
		llSave.setOnClickListener(this);
		llCancel.setOnClickListener(this);

	}

	private void callService(String text, String homeCurrency) {
		if (objReceipt != null) {
			String date = objReceipt.getDateTime();
			if (date.equals("") || date == null) {
				date = Util.getTodaysDate();
			}
			date = Util.formateDateFromstring("dd-MM-yyyy", "yyyy-MM-dd", date);
			if ("".equals(date) || date == null) {
				date = Util.getCurrentTime();
			}
			callAsynCallServiceGetCurrency(text, homeCurrency, date);
		}
	}

	/**
	 * get data in currency.txt what in asset
	 */
	private ArrayList<String> getAssetCurrency() {
		ArrayList<String> arrString = new ArrayList<String>();
		arrString = Util.readFromfile(ReceiptConverter.this, "currency.txt");
		ArrayList<String> arrCurrency = new ArrayList<String>();
		for (int i = 0; i < arrString.size(); i++) {
			String line = "";
			line = arrString.get(i);
			String[] lText = null;
			lText = line.split(":");
			line = lText[0];
			line = line.replace("\"", "");
			arrCurrency.add(line.trim());
			if (objReceipt.getCurrencyCode().equals(line.trim())) {
				row = i;
			}
		}
		return arrCurrency;
	}

	/**
	 * add Data UI
	 */

	private void addDataUI() {
		objReceipt = new ReceiptObj();
		objReceipt = (ReceiptObj) getIntent().getSerializableExtra(
				"RECEIPT_OBJ");
		if (objReceipt != null) {
			txtHomeDiscount.setText(objReceipt.getDiscount());
			txtHomeSubTotal.setText(objReceipt.getSubTotal());
			txtHomeTax.setText(objReceipt.getTax());
			txtHomeTotal.setText(objReceipt.getTotal());
		}
		homecurrency = getDataSqlite().getCurrencyCode();
		txtHomeCurrency.setText(homecurrency);
		txtPurDate.setText(objReceipt.getDateTime());
	}

	/**
	 * call sevirce get currency
	 */
	private void callAsynCallServiceGetCurrency(String fromCode, String toCode,
			String purchaseDate) {
		Model mModel = new Model(model, TaskType.TASK_GET_CURRENCY_CONVERTER,
				null, this);
		String[] mParams = { fromCode, toCode, purchaseDate };
		TaskParams params = new TaskParams(mParams);
		if (Util.isNetworkActivated(ReceiptConverter.this)) {
			llContent.setVisibility(View.GONE);
			llBottom.setVisibility(View.GONE);
			pbLoad.setVisibility(View.VISIBLE);
			model.exeTask(params, mModel);
		} else {
			showToast(getString(R.string.no_connection));
		}
	}

	@Override
	public void onSuccess(int taskType, ArrayList<?> list, String msg) {
		// TODO Auto-generated method stub
		super.onSuccess(taskType, list, msg);
		switch (taskType) {
		case TaskType.TASK_GET_CURRENCY_CONVERTER:
			ArrayList<BaseObject> arrBaseObject = new ArrayList<BaseObject>();
			arrBaseObject = (ArrayList<BaseObject>) list;
			String rate = "";
			for (int i = 0; i < arrBaseObject.size(); i++) {
				rate = arrBaseObject.get(i).getParam("exchangeRate");
			}
			txtRate.setText(rate + "");
			txtConvertSubTotal.setText(Util.formatStringFloat(Util
					.convertFloat(rate)
					* Util.convertFloat(txtHomeSubTotal.getText().toString())));
			txtConvertTax.setText(Util.formatStringFloat(Util
					.convertFloat(rate)
					* Util.convertFloat(txtHomeTax.getText().toString())));
			txtConvertTotal.setText(Util.formatStringFloat(Util
					.convertFloat(rate)
					* Util.convertFloat(txtHomeTotal.getText().toString())));
			txtConvertDiscount.setText(Util.formatStringFloat((Util
					.convertFloat(rate) * Util.convertFloat(txtHomeDiscount
					.getText().toString()))));
			llContent.setVisibility(View.VISIBLE);
			llBottom.setVisibility(View.VISIBLE);
			pbLoad.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

	/**
	 * Update item by rate
	 */
	private void convertItem(float rate) {
		ArrayList<tbl_Item> arrItem = new ArrayList<tbl_Item>();
		arrItem = DatabaseSupport.getItemsByReceiptID(
				objReceipt.getReceiptID(), ReceiptConverter.this);
		if (arrItem != null) {
			for (tbl_Item objItem : arrItem) {
				float amount = Util.convertFloat(objItem.getAmount()) * rate;
				objItem.setAmount(Util.formatStringFloat(amount));
				objItem.setIsUpdate("1");
				DatabaseSupport.updateItem(objItem, ReceiptConverter.this);
			}
		}
	}

	/**
	 * Update receipt by rate
	 */
	private int updateReceipt() {
		tbl_Receipt objReceipt = new tbl_Receipt();
		objReceipt = DatabaseSupport.getReceiptByID(
				this.objReceipt.getReceiptID(), ReceiptConverter.this);
		objReceipt.setIsUpdate("1");
		objReceipt.setTotal(txtConvertTotal.getText().toString());
		objReceipt.setTax(txtConvertTax.getText().toString());
		objReceipt.setDiscount(txtConvertDiscount.getText().toString());
		objReceipt.setSubtotal(txtConvertSubTotal.getText().toString());
		objReceipt.setCurrencyCode(spConverterNow.getSelectedItem().toString());
		return this.getContentResolver().update(
				Contract.CONTENT_URI_RECEIPT,
				objReceipt.getContentValues(),
				tbl_ReceiptDao.Properties.ReceiptID.columnName + " = "
						+ objReceipt.getReceiptID(), null);
	}

	/**
	 * get data tbl_setting in sqlite
	 */
	private tbl_Settings objSetting;

	private tbl_Settings getDataSqlite() {
		objSetting = new tbl_Settings();
		Cursor cursor = this.getContentResolver().query(
				Contract.CONTENT_URI_SETTING, null, null, null, null);
		objSetting = tbl_Settings.getObjectByCursor(cursor);
		return objSetting;
	}

	/**
	 * update home currency
	 */

	private int updateSetting() {
		if (objSetting == null) {
			return 0;
		}
		objSetting.setCurrencyCode(spConverterNow.getSelectedItem().toString());
		return this.getContentResolver().update(Contract.CONTENT_URI_SETTING,
				objSetting.getContentValues(), null, null);
	}

	@Override
	public void onFail(int taskType, String msg) {
		super.onFail(taskType, msg);
		showToast(msg);
		llContent.setVisibility(View.VISIBLE);
		llBottom.setVisibility(View.VISIBLE);
		pbLoad.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llCancel:
			finish();
			break;
		case R.id.llSave:
			if (updateReceipt() > 0 && updateSetting() > 0) {
				convertItem(Util.convertFloat(txtRate.getText().toString()));
				finish();
			}

			break;
		default:
			break;
		}
	}

}
